package ssm.controller;


import com.holiday.springboot2.utils.JsonData;
import org.springframework.web.bind.annotation.*;
import ssm.model.entity.User;
import ssm.model.request.LoginRequest;
import ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/pri/user")
public class UserController {


    @Autowired
    private UserService userService;

    @PostMapping("register")
    public JsonData register(@RequestBody Map<String, String> userInfo) {
        int rows = userService.save(userInfo);
        return rows == 1 ? JsonData.buildSuccess(rows) : JsonData.buildError("注册失败，请重试");

    }

    @PostMapping("login")
    public JsonData login(@RequestBody LoginRequest loginRequest) {
        // 通过电话与密码查询用户，如果查询到用户，则返回token
        String token = userService.findByPhoneAndPwd(loginRequest.getPhone(), loginRequest.getPwd());
        // 如果token 返回空，则返回失败
        return token == null ? JsonData.buildError("登录失败，账号密码错误") : JsonData.buildSuccess(token);
    }


    @GetMapping("find_by_token")
    public  JsonData findUserInfoByToken(HttpServletRequest request){
        // 拦截器中 解析了用户的信息，放到了request中，那么在controller中request就能获取到
        Integer user_id =(Integer)request.getAttribute("user_id");
        if(user_id==null){
            return JsonData.buildError("查询失败");
        }
        User user =userService.findByUserId(user_id);
        return JsonData.buildSuccess(user);

    }
}
